Page({
  data: {
    currentDate: '',
    classList: [{ id: 0, name: '全部班级' }],
    classIndex: 0,
    statistics: {
      total: 0,
      present: 0,
      absent: 0,
      late: 0
    },
    attendanceList: [],
    showEditModal: false,
    currentStudent: {},
    statusOptions: ['正常', '迟到', '早退', '请假', '缺勤'],
    statusIndex: 0,
    checkinTime: '',
    remark: '',
    // 新增日期范围选择相关状态
    showDateRangePicker: false,
    startDate: '',
    endDate: ''
  },

  onLoad: function() {
    // 设置当前日期
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    
    this.setData({
      currentDate: `${year}-${month}-${day}`,
      // 确保统计数据初始化为数字类型
      statistics: {
        total: 0,
        present: 0,
        late: 0,
        absent: 0
      }
    });
    
    // 获取班级列表
    this.fetchClassList();
    
    // 获取考勤数据
    this.fetchAttendanceData();
  },

  onReady() {
    // 页面渲染完成
  },

  onShow() {
    // 页面显示
  },

  // 获取班级列表
  fetchClassList: function() {
    wx.request({
      url: 'http://localhost:3000/api/admin/classes',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const classes = [{ id: 0, name: '全部班级' }, ...res.data];
          this.setData({
            classList: classes
          });
        }
      }
    });
  },

  // 获取考勤数据
  fetchAttendanceData: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    const app = getApp();
    const classId = this.data.classList[this.data.classIndex].id;
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/admin/attendance`,
      method: 'GET',
      data: {
        date: this.data.currentDate,
        classId: classId === 0 ? '' : classId
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          console.log('原始统计数据:', res.data.statistics);
          
          // 确保统计数据为数字类型
          const statistics = {
            total: parseInt(res.data.statistics.total || 0),
            present: parseInt(res.data.statistics.present || 0),
            late: parseInt(res.data.statistics.late || 0),
            absent: parseInt(res.data.statistics.absent || 0)
          };
          
          console.log('转换后的统计数据:', statistics);
          
          this.setData({
            attendanceList: res.data.records || [],
            statistics: statistics
          });
          
          console.log('设置后的数据:', this.data.statistics);
        } else {
          wx.showToast({
            title: res.data.message || '获取考勤数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取考勤数据失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 导出考勤数据
  exportAttendance: function() {
    // 显示导出选项
    wx.showActionSheet({
      itemList: ['导出当前日期', '导出本周', '导出本月', '自定义日期范围'],
      success: (res) => {
        const index = res.tapIndex;
        if (index === 0) {
          // 导出当前日期
          this.doExportAttendance({
            date: this.data.currentDate
          });
        } else if (index === 1) {
          // 导出本周
          const today = new Date(this.data.currentDate);
          const dayOfWeek = today.getDay() || 7; // 获取星期几，星期日为0转为7
          const startDate = new Date(today);
          startDate.setDate(today.getDate() - dayOfWeek + 1); // 计算本周一
          
          const endDate = new Date(today);
          endDate.setDate(today.getDate() + (7 - dayOfWeek)); // 计算本周日
          
          this.doExportAttendance({
            startDate: this.formatDate(startDate),
            endDate: this.formatDate(endDate)
          });
        } else if (index === 2) {
          // 导出本月
          const today = new Date(this.data.currentDate);
          const year = today.getFullYear();
          const month = today.getMonth();
          
          const startDate = new Date(year, month, 1);
          const endDate = new Date(year, month + 1, 0);
          
          this.doExportAttendance({
            startDate: this.formatDate(startDate),
            endDate: this.formatDate(endDate)
          });
        } else if (index === 3) {
          // 自定义日期范围
          this.showDateRangePicker();
        }
      }
    });
  },

  // 执行导出操作
  doExportAttendance: function(params) {
    wx.showLoading({
      title: '准备导出...',
    });
    
    const app = getApp();
    const classId = this.data.classList[this.data.classIndex].id;
    
    // 添加班级ID
    if (classId !== 0) {
      params.classId = classId;
    }
    
    console.log('导出考勤请求参数:', params);
    
    // 构建下载链接
    let downloadUrl = `${app.globalData.serverUrl}/api/admin/attendance/export?`;
    
    // 添加参数到URL
    if (params.date) {
      downloadUrl += `date=${params.date}&`;
    }
    if (params.startDate) {
      downloadUrl += `startDate=${params.startDate}&`;
    }
    if (params.endDate) {
      downloadUrl += `endDate=${params.endDate}&`;
    }
    if (params.classId) {
      downloadUrl += `classId=${params.classId}&`;
    }
    
    // 使用小程序的下载文件API
    wx.downloadFile({
      url: downloadUrl,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200) {
          // 打开文件
          wx.openDocument({
            filePath: res.tempFilePath,
            fileType: 'xlsx',
            success: function() {
              console.log('打开文档成功');
              wx.showToast({
                title: '导出成功',
                icon: 'success'
              });
            },
            fail: function(error) {
              console.error('打开文档失败:', error);
              wx.showToast({
                title: '无法打开文件',
                icon: 'none'
              });
            }
          });
        } else {
          wx.showToast({
            title: '导出失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('下载文件失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '导出失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 尝试使用后端导出功能
  tryServerExport: function(params) {
    wx.showLoading({
      title: '尝试后端导出...',
    });
    
    const app = getApp();
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/admin/attendance/export`,
      method: 'GET',
      data: params,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          // 获取文件下载链接
          const fileUrl = res.data.fileUrl;
          const recordCount = res.data.recordCount || '未知';
          
          // 在小程序中无法直接下载文件到本地，可以提示用户在网页中下载
          wx.showModal({
            title: '导出成功',
            content: `已成功导出${recordCount}条考勤记录，请在浏览器中打开链接下载`,
            confirmText: '复制链接',
            success: (result) => {
              if (result.confirm) {
                wx.setClipboardData({
                  data: fileUrl,
                  success: () => {
                    wx.showToast({
                      title: '链接已复制',
                      icon: 'success'
                    });
                  }
                });
              }
            }
          });
        } else {
          console.error('后端导出失败:', res.data);
          wx.showToast({
            title: res.data.message || '后端导出失败，已使用前端导出',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: (err) => {
        console.error('后端导出请求失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '后端导出失败，已使用前端导出',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  // 显示日期范围选择器
  showDateRangePicker: function() {
    this.setData({
      showDateRangePicker: true,
      startDate: this.data.currentDate,
      endDate: this.data.currentDate
    });
  },
  
  // 开始日期变更
  startDateChange: function(e) {
    this.setData({
      startDate: e.detail.value
    });
  },
  
  // 结束日期变更
  endDateChange: function(e) {
    this.setData({
      endDate: e.detail.value
    });
  },
  
  // 确认日期范围
  confirmDateRange: function() {
    if (new Date(this.data.startDate) > new Date(this.data.endDate)) {
      wx.showToast({
        title: '开始日期不能晚于结束日期',
        icon: 'none'
      });
      return;
    }
    
    this.doExportAttendance({
      startDate: this.data.startDate,
      endDate: this.data.endDate
    });
    
    this.setData({
      showDateRangePicker: false
    });
  },
  
  // 取消日期范围选择
  cancelDateRange: function() {
    this.setData({
      showDateRangePicker: false
    });
  },
  
  // 格式化日期为YYYY-MM-DD
  formatDate: function(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 查看统计
  viewStatistics: function() {
    wx.navigateTo({
      url: '/pages/admin/attendance/statistics/statistics'
    });
  },

  // 编辑考勤记录
  editAttendance: function(e) {
    const attendanceId = e.currentTarget.dataset.id;
    const attendance = this.data.attendanceList.find(item => item.id === attendanceId);
    
    if (attendance) {
      // 设置当前选中的学生和状态
      let statusIndex = 0;
      switch(attendance.status) {
        case 'present': statusIndex = 0; break; // 正常
        case 'late': statusIndex = 1; break;    // 迟到
        case 'early': statusIndex = 2; break;   // 早退
        case 'leave': statusIndex = 3; break;   // 请假
        case 'absent': statusIndex = 4; break;  // 缺勤
        default: statusIndex = 0;
      }
      
      // 处理签到时间
      let checkinTime = '';
      if (attendance.checkInTime) {
        // 提取时间部分 (HH:MM)
        const timeMatch = attendance.checkInTime.match(/\d{2}:\d{2}/);
        checkinTime = timeMatch ? timeMatch[0] : '';
      }
      
      this.setData({
        showEditModal: true,
        currentStudent: {
          id: attendance.id,
          studentId: attendance.studentId,
          name: attendance.studentName,
          studentNumber: attendance.studentNumber,
          className: attendance.className,
          originalStatus: attendance.status
        },
        statusIndex: statusIndex,
        checkinTime: checkinTime,
        remark: attendance.remark || ''
      });
      
      console.log('编辑考勤记录:', attendance);
      console.log('设置的时间:', checkinTime);
    } else {
      wx.showToast({
        title: '未找到考勤记录',
        icon: 'none'
      });
    }
  },

  // 保存考勤修改
  saveAttendance: function() {
    const app = getApp();
    const statusMap = ['present', 'late', 'early', 'leave', 'absent'];
    const newStatus = statusMap[this.data.statusIndex];
    
    // 验证数据
    if (newStatus !== 'absent' && newStatus !== 'leave' && !this.data.checkinTime) {
      wx.showToast({
        title: '请选择签到时间',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '保存中...',
    });
    
    // 准备请求数据
    const requestData = {
      status: newStatus,
      remark: this.data.remark
    };
    
    // 只有非缺勤状态才设置签到时间
    if (newStatus !== 'absent') {
      requestData.checkInTime = this.data.checkinTime ? 
        `${this.data.currentDate} ${this.data.checkinTime}:00` : null;
    }
    
    console.log('发送修改请求:', {
      url: `${app.globalData.serverUrl}/api/admin/attendance/${this.data.currentStudent.id}`,
      data: requestData
    });
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/admin/attendance/${this.data.currentStudent.id}`,
      method: 'PUT',
      data: requestData,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          wx.showToast({
            title: '修改成功',
            icon: 'success'
          });
          
          // 关闭弹窗
          this.setData({
            showEditModal: false
          });
          
          // 重新获取考勤数据
          this.fetchAttendanceData();
        } else {
          console.error('修改失败:', res.data);
          wx.showToast({
            title: res.data.message || '修改失败，请联系管理员',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('修改考勤记录失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 关闭弹窗
  closeModal: function() {
    this.setData({
      showEditModal: false
    });
  },

  // 状态选择变更
  statusChange: function(e) {
    const newIndex = parseInt(e.detail.value);
    this.setData({
      statusIndex: newIndex
    });
    
    // 如果选择了缺勤，清空签到时间
    if (newIndex === 4) { // 缺勤
      this.setData({
        checkinTime: ''
      });
    }
  },

  // 签到时间变更
  timeChange: function(e) {
    this.setData({
      checkinTime: e.detail.value
    });
  },

  // 备注输入
  remarkInput: function(e) {
    this.setData({
      remark: e.detail.value
    });
  },

  // 日期变更
  dateChange: function(e) {
    this.setData({
      currentDate: e.detail.value
    });
    
    this.fetchAttendanceData();
  },

  // 班级变更
  classChange: function(e) {
    this.setData({
      classIndex: e.detail.value
    });
    
    this.fetchAttendanceData();
  },

  onReachBottom() {
    // 页面上拉触底事件的处理函数
  }
});